package com.equipmentRent.web.controller.system;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.equipmentRent.common.core.domain.entity.SysUser;
import com.equipmentRent.common.utils.ShiroUtils;
import com.equipmentRent.system.domain.Item;
import com.equipmentRent.system.domain.VO.OrderAmountVo;
import com.equipmentRent.system.domain.VO.UserCartVo;
import com.equipmentRent.system.domain.dto.AddShopCartDto;
import com.equipmentRent.system.domain.dto.CartSelectedDto;
import com.equipmentRent.system.domain.dto.SelectedCartItemDto;
import com.equipmentRent.system.domain.dto.UpdateCartItemQuantityDto;
import com.equipmentRent.system.service.IItemService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.equipmentRent.common.annotation.Log;
import com.equipmentRent.common.enums.BusinessType;
import com.equipmentRent.system.domain.BizCart;
import com.equipmentRent.system.service.IBizCartService;
import com.equipmentRent.common.core.controller.BaseController;
import com.equipmentRent.common.core.domain.AjaxResult;
import com.equipmentRent.common.utils.poi.ExcelUtil;
import com.equipmentRent.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 租购置单Controller
 * 
 * @author ruoyi
 * @date 2025-05-24
 */
@Controller
@RequestMapping("/system/cart")
public class BizCartController extends BaseController
{
    private String prefix = "system/cart";

    @Autowired
    private IBizCartService bizCartService;

    @Resource
    private IItemService productService;

    @RequiresPermissions("system:cart:view")
    @GetMapping()
    public String cart()
    {
        return prefix + "/cart";
    }

    /**
     * 查询租购置单列表
     */
    @RequiresPermissions("system:cart:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BizCart bizCart)
    {
        startPage();
        List<BizCart> list = bizCartService.selectBizCartList(bizCart);
        return getDataTable(list);
    }

    /**
     * 导出租购置单列表
     */
    @RequiresPermissions("system:cart:export")
    @Log(title = "租购置单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BizCart bizCart)
    {
        List<BizCart> list = bizCartService.selectBizCartList(bizCart);
        ExcelUtil<BizCart> util = new ExcelUtil<BizCart>(BizCart.class);
        return util.exportExcel(list, "租购置单数据");
    }

    /**
     * 新增租购置单
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 添加购物车
     */
    @PostMapping("/addCart")
    @ResponseBody
    public AjaxResult addCart(@RequestBody AddShopCartDto addShopCartDto){
        if (ObjectUtils.isEmpty(addShopCartDto) || ObjectUtils.isEmpty(addShopCartDto.getProductId())){
            return error("请求参数错误~");
        }
        SysUser sysUser = ShiroUtils.getSysUser();
        if (ObjectUtils.isEmpty(sysUser)){
            return error("当前属于游客模式,请先登录~");
        }
        Item bizProduct = productService.selectItemById(Long.valueOf(addShopCartDto.getProductId()));
        BizCart bizCart = new BizCart();
        bizCart.setProductId(Long.valueOf(addShopCartDto.getProductId()));
        bizCart.setUserId(sysUser.getUserId());
        if (ObjectUtils.isEmpty(bizProduct)){
            return error("添加的器材不存在~");
        }
        bizCart.setQuantity(1L);
        int i = bizCartService.insertBizCart(bizCart);
        if (i > 0){
            return AjaxResult.success(i);
        }
        return error("添加失败~");
    }

    /**
     * 获取购物车选中的器材金额
     * @return
     */
    @PostMapping("/getSelectedAmount")
    @ResponseBody
    public AjaxResult getSelectedAmount() {
        SysUser sysUser = ShiroUtils.getSysUser();
        if (ObjectUtils.isEmpty(sysUser)) {
            return error("当前属于游客模式,请先登录~");
        }

        Long userId = ShiroUtils.getUserId();
        List<BizCart> bizCartList = bizCartService.selectBizCartByUserId(userId);

        if (ObjectUtils.isEmpty(bizCartList)) {
            return AjaxResult.success(OrderAmountVo.builder().amount(BigDecimal.ZERO).deposit(BigDecimal.ZERO).build());
        }

        // 获取所有商品ID
        List<Long> productIds = bizCartList.stream()
                .map(BizCart::getProductId)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询商品信息
        List<Item> productList = productService.selectItemsByIds(productIds);
        Map<Long, Item> productMap = productList.stream()
                .collect(Collectors.toMap(Item::getId, Function.identity()));

        // 计算总金额和押金
        BigDecimal amount = bizCartList.stream()
                .map(cart -> {
                    Item item = productMap.get(cart.getProductId());
                    return item.getDailyRate().multiply(new BigDecimal(cart.getQuantity() * 7L));
                })
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal deposit = bizCartList.stream()
                .map(cart -> {
                    Item item = productMap.get(cart.getProductId());
                    return item.getDeposit().multiply(new BigDecimal(cart.getQuantity()));
                })
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        OrderAmountVo build = OrderAmountVo.builder()
                .amount(amount)
                .deposit(deposit)
                .build();

        return AjaxResult.success(build);
    }

    /**
     * 查询用户购物车列表
     */
    @PostMapping("/getCartList")
    @ResponseBody
    public AjaxResult getCartList(){
        List<UserCartVo> userCartVos = new ArrayList<>();
        SysUser sysUser = ShiroUtils.getSysUser();
        if (ObjectUtils.isEmpty(sysUser)){
            return error("当前属于游客模式,请先登录~");
        }
        BizCart bizCart = new BizCart();
        bizCart.setUserId(sysUser.getUserId());
//        获取购物车列表
        List<BizCart> bizCartList = bizCartService.selectBizCartList(bizCart);
//        查询商品信息
        bizCartList.forEach(item -> {
            Item bizProduct = productService.selectItemById(item.getProductId());
            UserCartVo build = UserCartVo.builder()
                    .id(item.getId())
                    .name(bizProduct.getName())
                    .price(bizProduct.getDailyRate().toString())
                    .quantity(item.getQuantity().toString())
                    .image(bizProduct.getImgUrl())
                    .selected(item.getSelected() == 1)
                    .productId(bizProduct.getId().toString())
                    .build();
            userCartVos.add(build);
        });
        return success(userCartVos);
    }

    /**
     * 更新购物车商品数量
     * @param updateCartItemQuantityDto
     * @return
     */
    @PostMapping("/updateCartItemQuantity")
    @ResponseBody
    public AjaxResult updateCartItemQuantity(@RequestBody UpdateCartItemQuantityDto updateCartItemQuantityDto){
        if (ObjectUtils.isEmpty(updateCartItemQuantityDto)
                || ObjectUtils.isEmpty(updateCartItemQuantityDto.getCartId())
                || ObjectUtils.isEmpty(updateCartItemQuantityDto.getType())) {
            return error("请求参数错误~");
        }
        try{
            String type = updateCartItemQuantityDto.getType();
            if ("delete".equals(type)){
                int i = bizCartService.softDeleteBizCartByIds(updateCartItemQuantityDto.getCartId());
            }
            if ("add".equals(type)){
                int i = bizCartService.addCartItemQuantity(updateCartItemQuantityDto.getCartId());
            }
            if ("remove".equals(type)){
                int i = bizCartService.removeCartItemQuantity(updateCartItemQuantityDto.getCartId());
            }
            return success("操作成功~");
        }catch (Exception e){
            return error("操作失败~");
        }
    }


    /**
     * 选中购物车
     * @param selectedCartItemDto
     * @return
     */
    @PostMapping("/selectedCartItem")
    @ResponseBody
    public AjaxResult selectedCartItem(@RequestBody SelectedCartItemDto selectedCartItemDto){
        if (ObjectUtils.isEmpty(selectedCartItemDto)) {
            return error("请求参数错误~");
        }
        SysUser sysUser = ShiroUtils.getSysUser();

        if (ObjectUtils.isEmpty(sysUser)){
            return error("当前属于游客模式,请先登录~");
        }

//        获取当前用户的购物
        BizCart bizCart = new BizCart();
        bizCart.setUserId(sysUser.getUserId());
        List<BizCart> bizCartList = bizCartService.selectBizCartList(bizCart);

        try{
            List<CartSelectedDto> cartSelectedDtoList = selectedCartItemDto.getCartSelectedDtoList();
//            把cartSelectedDtoList转换成map
            Map<String, CartSelectedDto> bizCartMap = cartSelectedDtoList.stream().collect(Collectors.toMap(CartSelectedDto::getCartId, Function.identity()));
            bizCartList.forEach(item -> {

                if (bizCartMap.containsKey(item.getId().toString())){
                    item.setSelected(1);
                }else {
                    item.setSelected(0);
                }
                bizCartService.updateBizCart(item);
            });
            return success("操作成功~");
        }catch (Exception e){
            return error("操作失败~");
        }
    }
    /**
     * 新增保存租购置单
     */
    @RequiresPermissions("system:cart:add")
    @Log(title = "租购置单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(BizCart bizCart)
    {
        return toAjax(bizCartService.insertBizCart(bizCart));
    }

    /**
     * 修改租购置单
     */
    @RequiresPermissions("system:cart:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        BizCart bizCart = bizCartService.selectBizCartById(id);
        mmap.put("bizCart", bizCart);
        return prefix + "/edit";
    }

    /**
     * 修改保存租购置单
     */
    @RequiresPermissions("system:cart:edit")
    @Log(title = "租购置单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(BizCart bizCart)
    {
        return toAjax(bizCartService.updateBizCart(bizCart));
    }

    /**
     * 删除租购置单
     */
    @RequiresPermissions("system:cart:remove")
    @Log(title = "租购置单", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(bizCartService.softDeleteBizCartByIds(ids));
    }
}
